/*
 * Heap.cpp
 *
 *  Created on: Sep 16, 2012
 *      Author: romina
 */

#include "Heap.h"

namespace ordenamiento {

Heap::Heap(Buffer * buffer){
	this->heap = buffer;
	this->tamanio = buffer->getCantidad();
	this->last = buffer->getCantidad() - 1;
}

void Heap::restaurarLast(){
	this->last = this->tamanio - 1;
}

void Heap::decreaseLast(){
	this->last--;
}

void Heap::swapRaizLast(){
	this->heap->swap(0, this->last);
	//this->swap(0, this->last);
}

string Heap::getRaiz(){
	return this->getValue(0);
}

string Heap::getValue(int pos){
	return this->heap->getDato(pos);
}

void Heap::setValue(int pos, string value){

	this->heap->addDato(pos, value);
}

int Heap::getLast(){
	return this->last;
}

void Heap::setLast(int last){
	this->last = last;
}

int Heap::getSize(){
	return this->tamanio;
}

bool Heap::isLeaf(int pos){
	return pos == this->last || pos > (this->last-1) / 2;
}

int Heap::rightH(int pos){
	return 2 * pos + 2;
}

int Heap::leftH(int pos){
	return 2 * pos + 1;
}

int Heap::parent(int pos){
	if (pos <= 0) {
		return -1;
	}
	return (pos-1)/2;
}

void Heap::swap(int pos1, int pos2){
	this->heap->swap(pos1, pos2);
}


void Heap::siftdown(int pos){
	int hijoIzq = leftH(pos);
	int hijoDer = rightH(pos);
	int menor = pos;
	if ((hijoIzq <= this->last) && (this->heap->getDato(hijoIzq).compare(this->heap->getDato(menor))) < 0)
		menor = hijoIzq;
	if ((hijoDer <= this->last) && (this->heap->getDato(hijoDer).compare(this->heap->getDato(menor))) < 0)
		menor = hijoDer;
	if(menor != pos){
		swap(pos, menor);
		siftdown(menor);
	}
}

void Heap::shiftLeft(int position){
	for (int i = 0; i + position < this->getLast(); i++){
			this->setValue(i, this->getValue(i+position));
	}
}

void Heap::buildheap(){
	for (int i = (this->last)/2; i >=0; i--){
			siftdown(i);
	}
}

Heap::~Heap() {
}

} /* namespace ordenamiento */
